<template>
  <div>
    <a-card :bordered="false">
      <a-descriptions bordered :column="2">
        <a-descriptions-item label="产品名称" :span="1">{{ product.name }}</a-descriptions-item>
        <a-descriptions-item label="渠道" :span="1">{{ product.platform }}</a-descriptions-item>
        <a-descriptions-item label="发行机构" :span="1">{{ product.issuer }}</a-descriptions-item>
        <a-descriptions-item label="更新日期" :span="1">{{ product.updateDate }}</a-descriptions-item>
      </a-descriptions>

      <div style="margin-top: 16px;">
        <h3>年化趋势</h3>
        <div style="max-height:320px;overflow:auto;">
          <a-table 
            :columns="rateColumns" 
            :dataSource="product.rateHistory || []" 
            rowKey="date" 
            :pagination="false"
            size="small"
          >
          </a-table>
        </div>
      </div>

      <div style="margin-top: 16px;">
        <h3>净值列表</h3>
        <a-button style="margin-bottom:16px;" type="primary" @click="openNavModal('add')">新增净值</a-button>
        <div>
          <a-table 
            :columns="navColumns" 
            :dataSource="navs" 
            rowKey="date" 
            :pagination="false"
            size="small"
            :scroll="{ y: 420 }"
          >
            <template slot="action" slot-scope="text, record">
              <a @click="openNavModal('edit', record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="deleteNav(record)">删除</a>
            </template>
          </a-table>
        </div>
      </div>

      <a-modal
        :title="navModalType === 'add' ? '新增净值' : '编辑净值'"
        v-model="navModalVisible"
        @ok="handleNavModalOk"
        :destroyOnClose="true"
      >
        <a-form :form="navForm" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <a-form-item label="日期">
            <a-date-picker
              v-decorator="['date', { 
                initialValue: navModalType === 'edit' ? moment(selectedNav.date) : defaultDate(),
                rules: [{ required: true, message: '请选择日期' }]
              }]"
              style="width: 100%"
              :locale="locale"
            />
          </a-form-item>
          <a-form-item label="净值">
            <a-input-number
              v-decorator="['nav', { 
                initialValue: navModalType === 'edit' ? selectedNav.nav : null,
                rules: [
                  { required: true, message: '请输入净值' },
                  { type: 'number', message: '净值必须为数字' },
                  { validator: (rule, value, callback) => {
                    if (value <= 0) {
                      callback('净值必须大于0');
                    } else {
                      callback();
                    }
                  }}
                ]
              }]"
              style="width: 100%"
              :min="0"
              :step="0.0001"
              :precision="6"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { fetchProductDetail } from '@/api/product';
import request from '@/api/request';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';

// 设置moment为中文
moment.locale('zh-cn');

export default {
  name: 'ProductNavs',
  props: {
    productId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      product: {},
      navs: [],
      navModalVisible: false,
      navModalType: 'add',
      navForm: this.$form.createForm(this),
      navColumns: [
        {
          title: '日期',
          dataIndex: 'date',
          key: 'date',
          width: 120,
           customRender: t => moment(t).format('YYYY-MM-DD')
        },
        {
          title: '净值',
          dataIndex: 'nav',
          key: 'nav',
          width: 120
        },
        {
          title: '操作',
          key: 'action',
          width: 120,
          scopedSlots: { customRender: 'action' }
        }
      ],
      rateColumns: [
        {
          title: '日期',
          dataIndex: 'date',
          key: 'date'
        },
        {
          title: '7日年化',
          dataIndex: 'rate7d',
          key: 'rate7d'
        },
        {
          title: '1月年化',
          dataIndex: 'rate1m',
          key: 'rate1m'
        },
        {
          title: '3月年化',
          dataIndex: 'rate3m',
          key: 'rate3m'
        },
        {
          title: '1万收益',
          dataIndex: 'income10k',
          key: 'income10k'
        },
        {
          title: '7日万收日均',
          dataIndex: 'income10k7dAvg',
          key: 'income10k7dAvg'
        },
        {
          title: '1月万收日均',
          dataIndex: 'income10k1mAvg',
          key: 'income10k1mAvg'
        }
      ],
      locale,
      moment
    };
  },
  methods: {
    defaultDate() {
      const isMonday = moment().day() === 1
      const confirmDays = isMonday ? this.product.confirmDays + 2 : this.product.confirmDays;
      return moment().subtract(confirmDays, 'days');
    },
    async fetchDetail() {
      const res = await fetchProductDetail(this.productId);
      console.log('产品详情数据:', res);
      this.product = res || {};
      this.navs = this.product.navs || [];
      if (this.product.rateHistory) {
        this.product.rateHistory.sort((a, b) => this.moment(b.date).unix() - this.moment(a.date).unix());
      }
    },
    openNavModal(type, record) {
      this.navModalType = type;
      if (type === 'edit' && record) {
        this.selectedNav = { ...record, date: this.moment(record.date) };
      } else {
        this.selectedNav = { date: this.moment(), nav: null };
      }
      this.navModalVisible = true;
    },
    handleNavModalOk(e) {
      e.preventDefault();
      this.navForm.validateFields((err, values) => {
        if (!err) {
          if (this.navModalType === 'add') {
            this.addNav(values);
          } else {
            this.updateNav(values);
          }
        }
      });
    },
    async addNav(values) {
      await request.post(`/product/${this.productId}/nav`, {
        date: values.date.format ? values.date.format('YYYY-MM-DD') : values.date,
        nav: values.nav,
        type: 'add'
      });
      this.navModalVisible = false;
      await this.fetchDetail();
      this.$emit("click", { msg: "净值更新" })
    },
    async updateNav(values) {
      await request.post(`/product/${this.productId}/nav`, {
        nav: values.nav,
        date: values.date.format ? values.date.format('YYYY-MM-DD') : values.date,
        type: 'update'
      });
      this.navModalVisible = false;
      await this.fetchDetail();
      this.$emit("click", { msg: "净值更新" })
    },
    async deleteNav(record) {
      await request.post(`/product/${this.productId}/nav/delete`,{ date: record.date });
      await this.fetchDetail();
    }
  },
  watch: {
    productId: {
      handler(newVal) {
        if (newVal) {
          this.fetchDetail();
        }
      },
      immediate: true
    }
  }
};
</script>

<style lang="less" scoped>
:deep(.ant-calendar-picker) {
  .ant-input {
    &[aria-hidden="true"] {
      display: none !important;
    }
  }
}

:deep(.ant-calendar) {
  .ant-calendar-input-wrap {
    &[aria-hidden="true"] {
      display: none !important;
    }
  }
}
</style>